<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class CommitteesController extends AppController {

    /**
     * Define $name
     *
     */
    var $name = 'Committees';
    /**
     * Define $helpers
     *
     */
    var $helpers = array('Html', 'Form', 'Text','Javascript','Ajax','DatePicker','iCal');
    var $components = array('RequestHandler');
    /**
     * Define $uses
     *
     */
    var $uses = array('Committee','Systemtodo','Template','Announcement','Meeting','User','Minutetype');
    
    var $paginate = array('limit'=>5);

    /**
     * Describe index
     *
     * @return null
     */
    function index() {
        $this->Committee->recursive = 0;
        $this->set('committees', $this->paginate());
    }

    /**
     * Describe change
     *
     * @return null
     */
    function change() {
        if($_GET['committee']==-1){
            $this->Session->delete('CurCommittee');
        }
        else{
            $this->Session->write('CurCommittee',$_GET['committee']);
        }
        if(isset($_GET['alert'])){
            $this->redirect(array('action'=>'alert','controller'=>$_GET['cur_view']));
        }
        elseif(isset($_GET['addressbook'])){
            $this->redirect(array('action'=>'addressbook','controller'=>$_GET['cur_view']));
        }
        elseif(isset($_GET['userroles'])){
            $this->redirect(array('action'=>'userroles','controller'=>$_GET['cur_view']));
        }
        else{
            $this->redirect(array('controller'=>$_GET['cur_view']));
        }
    }

    /**
     * Describe view
     *
     * @param $id
     * @return null
     */
    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid Committee.', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->set('committee', $this->Committee->read(null, $id));
    }

    /**
     * Describe add
     *
     * @return null
     */
    function add() {

        if (!empty($this->data)) {
            $this->Committee->create();
            $this->data['Committee']['user_id']=$this->Auth->user('id');
            
            if ($this->Committee->save($this->data)) {
                $committee_id=$this->Committee->getLastInsertID();

                $this->Systemtodo->saveCommittee($committee_id,$this->Auth->user('id'));
                $this->Template->saveCommittee($committee_id);
                $this->Committee->Membership->saveCommittee($committee_id,$this->Auth->user('id'),Configure::read('defaultrole'));
                $lastMembershipId = $this->Committee->Membership->getLastInsertID();
                $this->Committee->query("UPDATE memberships SET order_id = 1 WHERE id =".$lastMembershipId );

                $this->Session->setFlash(__('The Committee has been saved', true));
                $this->redirect(array('controller'=>'memberships','committee'=>$this->data['Committee']['short_name']));
            } else {
                $this->Session->setFlash(__('The Committee could not be saved. Please, try again.', true));
            }
        }

        // find all minute format, put it in key=>value format for dropdown
        $this->set('minuteformat',$this->Minutetype->formatList());
    }

    /**
     * Describe edit
     *
     * @param $id
     * @return null
     */
    function edit($id = null) {
        $this->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Committee', true));
            $this->redirect(array('action'=>'mainpage'));
        }
        if (!empty($this->data)) {
            //if (empty($this->data['Committee']['parent_id'])) $this->data['Committee']['parent_id'] = 0;
            if ($this->Committee->save($this->data)) {
                $this->Session->setFlash(__('The Committee has been saved', true));
                $this->redirect(array('action'=>'mainpage'));
            } else {
                $this->Session->setFlash(__('The Committee could not be saved. Please, try again.', true));
            }
        }
        $mycommittees = $this->Committee->getCommittees($this->Auth->user('id'));
        $this->set('mycommittees',$mycommittees);
        if (empty($this->data)) {
            $this->data = $this->Committee->findByShortName($id);
        }
        $todos = $this->Committee->Todo->find('list');
        $users = $this->Committee->User->find('list');
        $this->set(compact('todos','users'));

        // find all minute format, put it in key=>value format for dropdown
        $this->set('minuteformat',$this->Minutetype->formatList());
        
        $this->set('dcommittee',$this->dcommittee);
    }

    /**
     * Describe delete
     *
     * @param $id
     * @return null
     */
    function delete($committee) {
        $dcommittee=$this->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        $this->Committee->delete($dcommittee['Committee']['id']);
        $this->Session->setFlash(__('Committee deleted', true));
        $this->redirect(array('controller'=>'committees','action'=>'mainpage'));
    }

    /**
     * Describe mainpage
     *
     * @return null
     */
    function mainpage(){
        $mycommittees = $this->Committee->getCommittees($this->Auth->user('id'),true);
        $user_id = $this->Auth->user('id');
        $pending_attendance=$this->Committee->Meeting->Attendance->user_attendance($user_id,null);
        foreach($pending_attendance as $pkey=>$pa){
            if(!array_key_exists($pa['Meeting']['committee_id'],$mycommittees)){
                unset($pending_attendance[$pkey]);
            }
        }
        $this->set('pending_attendance',$pending_attendance);
        $taken_attendance=$this->Committee->Meeting->Attendance->user_attendance($user_id,array(0,1,2));
        foreach($taken_attendance as $tkey=>$ta){
            if(!array_key_exists($ta['Meeting']['committee_id'],$mycommittees)){
                unset($taken_attendance[$tkey]);
            }
        }
        $this->set('taken_attendance',$taken_attendance);
        $pending_approval=$this->Committee->Meeting->Notification->find('all',array('fields'=>array('DISTINCT Notification.meeting_id','Meeting.*'),'conditions'=>array('type'=>array('send for approval','send for reapproval'),'to'=>$this->Auth->user('email'))));
        foreach($pending_approval as $akey=>$adata){
            if(!array_key_exists($adata['Meeting']['committee_id'],$mycommittees)){
                unset($pending_approval[$akey]);
            }elseif($this->Committee->Meeting->Notification->checkSent($adata['Notification']['meeting_id'],'minutes approved')){
                unset($pending_approval[$akey]);
            }else{
                $pending_approval[$akey]['Committee']['short_name']=$this->Committee->IdToShortName($adata['Meeting']['committee_id']);
            }
        }
        $this->set('pending_approval',$pending_approval);
        
        $this->Committee->Meeting->Notification->recursive=1;
        $minute_comment=$this->Committee->Meeting->Notification->find('all',array('conditions'=>array('type'=>'minute comment','to'=>$this->Auth->user('email'))));
        $min_comm_meeting_id=array_flip(Set::extract($minute_comment,'{n}.Notification.meeting_id'));
        foreach($minute_comment as $akey=>$adata){
            if(!in_array($akey,$min_comm_meeting_id)){
                unset($minute_comment[$akey]);
            }elseif((!empty($adata['Meeting'])) && !array_key_exists($adata['Meeting']['committee_id'],$mycommittees)){
                unset($minute_comment[$akey]);
            }elseif($this->Committee->Meeting->Notification->checkSent($adata['Notification']['meeting_id'],'minutes approved')){
                unset($minute_comment[$akey]);
            }elseif(($this->Committee->Meeting->Notification->find('count',array('conditions'=>array('type'=>'send for reapproval','notification_date>=\''.$adata['Notification']['notification_date'].'\'','Notification.meeting_id'=>$adata['Notification']['meeting_id']))))){
                unset($minute_comment[$akey]);
            }else{
                $minute_comment[$akey]['Committee']['short_name']=$this->Committee->IdToShortName($adata['Meeting']['committee_id']);
            }
        }
        $this->set('minute_comment',$minute_comment);
        
        foreach ($mycommittees as $key=>$com){
            if (strpos($key,'_details') === false) {
                $permission=$this->getPermission($key,$user_id);
                // append permission on the committee
                $mycommittees[$key.'_details']['0']['edit_committee'] = isset($permission['Committee']['Edit'])?$permission['Committee']['Edit']:0;
                $mycommittees[$key.'_details']['0']['delete_committee'] = isset($permission['Committee']['Delete'])?$permission['Committee']['Delete']:0;
                $mycommittees[$key.'_details']['0']['create_committee'] = isset($permission['Committee']['Create'])?$permission['Committee']['Create']:0;
                $mycommittees[$key.'_details']['0']['edit_wfmodels'] = isset($permission['Wfmodel']['Edit'])?$permission['Wfmodel']['Edit']:0;
                $mycommittees[$key.'_details']['0']['edit_announcements'] = isset($permission['Announcement']) && array_sum($permission['Announcement'])>0?1:0;
                $mycommittees[$key.'_details']['0']['edit_templates'] = isset($permission['Template']) && array_sum($permission['Template'])>0?1:0;
                $mycommittees[$key.'_details']['0']['edit_todos'] = isset($permission['Committeetodo']) && array_sum($permission['Committeetodo'])>0?1:0;
            }
        }
        $this->set('committees',$mycommittees);
    }

    /**
     * Describe alert
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function alert($committee,$id=null){
        $this->Committee->Meeting->Behaviors->detach('MultiFile');
        $this->Committee->Meeting->Behaviors->detach('Comment');
        $this->Committee->Meeting->unbindModel(array('hasMany'=>array('Decision','Todo','Notification'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);
        $this->Committee->Meeting->Decision->Behaviors->detach('MultiFile');
        $this->Committee->Meeting->Decision->Behaviors->detach('Comment');
        
        //upcoming meetings
        $upcoming=$this->Committee->Meeting->find(
            'all',
            array(
                'conditions'=>array(
                    'committee_id'=>$this->dcommittee['Committee']['id'],
                    'meeting_date>=now()',
                    "Meeting.deleted!='1'",
                ),
                'contain'=>false,
                'fields'=>array(
                    'meeting_num',
                    'id',
                    'meeting_title',
                    'meeting_date',
                    'venue',
                ),
            )
        );
        $this->set('upcoming',$upcoming);
        
        //upcoming status deadline
        $not=$this->Committee->deletedDecisionId();
        $this->Committee->Meeting->Decision->Behaviors->detach('Comment');
        $userstatus=array_diff($this->Committee->userDecision($this->dcommittee['Committee']['id'],$this->Auth->user('id')),$not);
        //$needupdating=$this->Committee->notUpdatedDecision($this->dcommittee['Committee']['id'],$this->Auth->user('id'),$userstatus);
        $upcomingdeadline=$this->Committee->Meeting->Decision->find(
            'all',array(
                'conditions'=>array(
                    'Decision.committee_id'=>$this->dcommittee['Committee']['id'],
                    'Decision.id'=>$userstatus,
                    'or'=>array(
                        'Decision.status_deadline>=now()',
                        'and'=>array(
                            'Decision.status_deadline'=>'0000-00-00',
                            'Decision.deadline>=now()',
                        )
                    ),
                    'not'=>array('Decision.id'=>$not)
                ),
                'contain'=>array(
                    'Item.name',
                    'Item.id',
                    'Meeting.meeting_num',
                    'Meeting.id',
                    'User.name',
                    'Group.name',
                ),
                'fields'=>array(
                    'Decision.id',
                    'Decision.description',
                    'Decision.deadline',
                    'Decision.status_deadline'
                )
            )
        );
        $this->set('upcomingdeadline',$upcomingdeadline);
        
        // need updating
        $this->set('needupdating',$this->Committee->needupdating($this->dcommittee['Committee']['id'],$this->Auth->user('id'),$userstatus));
        
        // announcement
        $announcement=$this->Committee->Announcement->find(
            'all',array(
                'conditions'=>array(
                    'committee_id'=>$this->dcommittee['Committee']['id'],
                ),
                'contain'=>array(
                    'User.name',
                ),
            )
        );
        $this->set('announcement',$announcement);
    }


    /**
     * Describe search
     *
     * @return null
     */
    function search() {
        $this->Committee->unbindModel(array('hasMany'=>array('Item','Group','Meeting','Decision','Announcement','Groupstatus','Wfmodel','Todo','Userstatus')),false);
        $this->Committee->unbindModel(array('hasAndBelongsToMany'=>array('User')),false);
        $this->Committee->Meeting->recursive=-1;
        $this->Committee->Meeting->Attendance->recursive=-1;
        $this->Meeting->Behaviors->detach('Comment');
        $this->Meeting->Behaviors->detach('multiFile');
        
        $this->Session->write('a',$this->data['Search']);
        //meeting option
        $meets=$this->Committee->Meeting->find('all',array('conditions'=>array('Meeting.committee_id'=>$this->dcommittee['Committee']['id'])));
        $meetings=array();
        foreach($meets as $m){
            $meetings[$m['Meeting']['id']]=$m['Meeting']['meeting_num'].' ('.date("Y-m-d",strtotime($m['Meeting']['meeting_date'])).')';
        }
        $this->set('meetings',$meetings);
        
        $attendance=$this->Committee->Meeting->Attendance->find('all',array('conditions'=>array('meeting_id'=>array_keys($meetings),'attend_as'=>2)));
        $chairperson=set::extract($attendance,'{n}.Attendance.user_id');
        $this->set('chairpersons',$this->Committee->User->find('list',array('conditions'=>array('User.id'=>array_unique($chairperson)))));
        if(!empty($this->data['Search']['from'])||!empty($this->data['Search']['to'])||!empty($this->data['Search']['meeting'])||!empty($this->data['Search']['chairperson'])||!empty($this->data['Search']['status'])||!empty($this->data['Search']['keyword'])){
            $cond="Decision.deleted=0";
        }
        //find conditions
        if(!empty($this->data['Search']['from'])){
            $this->set('cursearch2',$this->data['Search']['from']);
            if(!empty ($this->data['Search']['to'])){
                $this->set('cursearch3',$this->data['Search']['to']);
                $cond=" and Decision.deadline>='".date("Y-m-d 0-0-0",strtotime($this->data['Search']['from']))."' and  Decision.deadline<='".date("Y-m-d 23-59-59",strtotime($this->data['Search']['to']))."'";
            }else{
                $cond= " and Decision.deadline>='".date("Y-m-d 0-0-0",strtotime($this->data['Search']['from']))."'";
            }
        }elseif(!empty ($this->data['Search']['to'])){
            $this->set('cursearch3',$this->data['Search']['to']);
            $cond=" and Decision.deadline<='".date("Y-m-d 23-59-59",strtotime($this->data['Search']['to']))."'";
        }
        if(!empty($this->data['Search']['meeting'])){
            $this->set('cursearch1',$this->data['Search']['meeting']);
            $cond.=" and Decision.meeting_id =".$this->data['Search']['meeting'];
        }
        if(!empty($this->data['Search']['chairperson'])){
            $this->set('cursearch0',$this->data['Search']['chairperson']);
            $cond.=" and Decision.meeting_id in (";
            $no=array_count_values($chairperson);
            foreach($attendance as $a){
                if($a['Attendance']['user_id']==$this->data['Search']['chairperson']){
                     --$no[$this->data['Search']['chairperson']];
                     if($no[$this->data['Search']['chairperson']]==0){
                         $cond.=$a['Attendance']['meeting_id'].')';
                         break 1;
                     }else{
                         $cond.=$a['Attendance']['meeting_id'].',';
                     }
                }
            }
            
        }
        
        if (!empty($this->data['Search']['status'])) {
            $data_users=$this->Committee->{$this->data['Search']['status']}($this->dcommittee['Committee']['id'],'User',$cond);
            $data_grp=$this->Committee->{$this->data['Search']['status']}($this->dcommittee['Committee']['id'],'Group',$cond);
            $this->set('cursearch',$this->data['Search']['status']);
        }elseif(!empty($cond) || !empty($this->data['Search']['keyword'])){
            $data_users=$this->Committee->statusInDate($this->dcommittee['Committee']['id'],'User',$cond);
            $data_grp=$this->Committee->statusInDate($this->dcommittee['Committee']['id'],'Group',$cond);
        }
        
        if(!empty($this->data['Search']['keyword'])){
            foreach($data_users as $d=>$data){
                if(!strpos($data['Decision']['description'],$this->data['Search']['keyword']) && !strpos(' '.$data['UserStatus']['description'],$this->data['Search']['keyword'])){
                    unset($data_users[$d]);
                }
            }
            foreach($data_grp as $d=>$data){
                if(!strpos($data['Decision']['description'],$this->data['Search']['keyword']) && !strpos(' '.$data['GroupStatus']['description'],$this->data['Search']['keyword'])){
                    unset($data_grp[$d]);
                }
            }
        }
        $this->set('curkey',$this->data['Search']['keyword']);
        if (!empty($data_users)){$this->set('results',$data_users);}
        if (!empty($data_grp)) {$this->set('results_grp',$data_grp);}
    }

    /**
     * Describe calendar
     *
     * @param $committee
     * @return null
     */
    function calendar(){
        $this->User->recursive=-1;
        $this->Meeting->Behaviors->detach('Comment');
        $this->Meeting->recursive=0;
    }

    /**
     * Describe addsubcomm
     * Create sub committee under $committee_id
     *
     * @param $committee_id
     * @return null
     */
    function addsubcomm($committee_id) {
        $this->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Todo','Userstatus','Groupstatus','Wfmodel'),'hasAndBelongsToMany'=>array('User','Membership')),false);

        if (!empty($this->data)) {
            $this->Committee->create();
            $this->data['Committee']['item_name']='Project';
            if ($this->Committee->save($this->data)) {
                $committee_id=$this->Committee->getLastInsertID();
                $this->Systemtodo->saveCommittee($committee_id);
                $this->Template->saveCommittee($committee_id);
                $this->Committee->Membership->saveCommittee($committee_id,$this->Auth->user('id'),Configure::read('defaultrole'));
                $this->Session->setFlash(__('The sub-committee has been saved', true));
                $this->redirect(array('controller'=>'memberships','committee'=>$this->data['Committee']['short_name']));
            } else {
                $this->Session->setFlash(__('The sub-committee could not be saved. Please, try again.', true));
            }
        }
        // find all minute format, put it in key=>value format for dropdown
        $this->set('minuteformat',$this->Minutetype->formatList());
    }

     /**
     * Describe find
     * Search by keyword
     *
     * @return null
     */
    function find(){
        $dtext=$this->Committee->processSysmbol($this->data['Search']['text']);
        $this->set('dtext',$dtext);
        $this->Session->write('key',$dtext);
        $this->set('multi',$this->Committee->getMulti($dtext,$this->Auth->user('id')));
    }

    /**
     * Describe getmultidata
     * Autocomplete for keyword field in "find" page
     *
     * read $this->data['Search']['text'] --keyword field
     * @return autocompleted word
     */
    function getmultidata() {
        Configure::write('debug', 0); // dont want debug in ajax returned html
        if ($this->RequestHandler->isAjax()) {
            $this->Committee->recursive=-1;
            $dtext=$this->Committee->processSysmbol($this->data['Search']['text']);
            $this->set('multi_data',$this->Committee->getAuto($dtext,$this->Auth->user('id')));
            $this->set('dtext',$dtext);
            $this->Session->write('key',$dtext[1]);
            $this->render('getmultidata','ajax');
        }
    }
    
    function help(){
    }
    
    function cal($committee_id,$username=false){
        if(!empty($committee_id)){
            $this->Committee->recursive=-1;
            $name=$this->Committee->find('first',array('fields'=>array('name'),'conditions'=>array('id'=>$committee_id)));
            $name=str_replace(' ','_',$name['Committee']['name']);
            $this->Committee->Meeting->create_cal($committee_id);
        }else{
            $name=$username;
            $this->Committee->Meeting->create_usercal($this->Auth->user('id'),$username);
        }
        
        header( 'Content-Type: text/calendar; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename="'.$name.'.ics"' );
        header( 'Cache-Control: max-age=10' );
        readfile(WWW_ROOT . 'upload' . DS . 'ics'. DS . $name.'.ics');
        exit();
    }
    
    function ical(){
        /*if(!empty($committee_id)){
            $meetings=$this->find('all',array('conditions'=>array('Meeting.committee_id'=>$committee_id,'Meeting.deleted'=>0)));
            $this->Committee->recursive=-1;
            $name=$this->Committee->find('first',array('fields'=>array('name'),'conditions'=>array('id'=>$committee_id)));
            $name=str_replace(' ','_',$name['Committee']['name']);
        
        }else{*/
            $meetings=$this->Committee->Meeting->find('all',array('conditions'=>array('Meeting.deleted'=>0)));
            $name='MyMeeting';
        //}
        $this->set('name',$name);
        return $meetings;
    }
}
?>
